//
//
//

#include <stdlib.h>
#include "rsa/openssl/bn.h"
#include "rsa/openssl/ossl_typ.h"
#include "stock_trade_rsa_encrypt.h"

#ifdef __WINCE_OS_X_VERSION
#include "openssl/rsa.h"
#endif

static unsigned char *preCode(unsigned char *byData,int nLen)
{
	unsigned char *result;
	if(nLen % 2 == 0){
		unsigned char tmp;
		int i = 0;
		result = (unsigned char *)malloc(nLen / 2);
		//unsigned char code;
		for(;i<nLen; i++){
			tmp=byData[i];
			if(tmp>='0'&&tmp<='9'){
				tmp-='0';
			}
			else if(tmp>='A'&&tmp<='F'){
				tmp=tmp-'A'+10;
			}
			if(i%2==1){
				result[i/2]=(result[i/2]<<4)|tmp;
			}else {
				result[i/2]=tmp;
			}
		}
	}
	//OPENSSL_free(byData);
	return result;
}


char * RSA_Encrypt(unsigned char *pc_data,int ilen,unsigned char *pc_keyN,int ikNlen,unsigned char *pc_keyE,int ikElen)
{
	BIGNUM *publicKeyN = BN_new();
	BIGNUM *publicKeyE = BN_new();
	BIGNUM *plaintText = BN_new();
	BIGNUM *cryptographText = BN_new();
	BN_CTX *ctx = BN_CTX_new();
	unsigned char *publicKeyNTmp = preCode(pc_keyN,ikNlen);
	unsigned char *publicKeyETmp = preCode(pc_keyE,ikElen);
	char *result = 0;
	unsigned char * pTemp = 0;
	
	BN_bin2bn(publicKeyNTmp,ikNlen / 2,publicKeyN);
	BN_bin2bn(publicKeyETmp,ikElen / 2,publicKeyE);
	BN_bin2bn(pc_data,ilen,plaintText);
	BN_mod_exp(cryptographText,plaintText,publicKeyE,publicKeyN,ctx);
	BN_CTX_free(ctx);
	pTemp = (unsigned char *)BN_bn2hex(cryptographText);
	result = (char*)preCode(pTemp, 256);
	BN_free(publicKeyN);
	BN_free(publicKeyE);
	BN_free(plaintText);
	BN_free(cryptographText);
	free(publicKeyETmp);
	free(publicKeyNTmp);
	return result;
	
	//return NULL;
}
